roughtime 0.1.0

A no_std-capable Roughtime secure time-sync client with pluggable crypto backends
Documentation
//! The anti-rollback time floor.
//!
//! No time reported by a Roughtime server (or the OS clock) is trusted below this floor: a
//! machine cannot legitimately observe a time earlier than when this crate was built, and
//! [`HARDCODED_FLOOR_SECS`] is a belt-and-suspenders lower bound baked directly into source.
//!
//! By default (the `build-time-floor` feature disabled) the effective floor is simply
//! [`HARDCODED_FLOOR_SECS`] — a static value with no dependency on the build machine's clock,
//! keeping builds reproducible. Enabling `build-time-floor` additionally ratchets the floor
//! forward to the start (UTC) of the day the crate was built, at the cost of build
//! reproducibility — see `build.rs` for the mechanism and the crate-level docs for guidance on
//! which mode to pick.

use crate::error::Error;

/// The absolute, hardcoded anti-rollback floor: July 1, 2026 00:00:00 UTC, in Unix seconds.
///
/// This value must be kept in sync with the identical constant in `build.rs`.
pub const HARDCODED_FLOOR_SECS: u64 = 1_782_864_000;

include!(concat!(env!("OUT_DIR"), "/build_floor.rs"));

/// The effective anti-rollback floor: the later of [`HARDCODED_FLOOR_SECS`] and the build-time
/// floor (which is `0` — a no-op — unless the crate was built with the `build-time-floor`
/// feature enabled).
pub const EFFECTIVE_FLOOR_SECS: u64 = if HARDCODED_FLOOR_SECS > BUILD_FLOOR_SECS {
    HARDCODED_FLOOR_SECS
} else {
    BUILD_FLOOR_SECS
};

/// Rejects a candidate Unix timestamp (in seconds) that predates [`EFFECTIVE_FLOOR_SECS`].
///
/// # Errors
///
/// Returns [`Error::BeforeFloor`] if `candidate_secs` is earlier than the effective floor.
pub const fn check_floor(candidate_secs: u64) -> Result<(), Error> {
    if candidate_secs < EFFECTIVE_FLOOR_SECS {
        Err(Error::BeforeFloor {
            candidate_secs,
            floor_secs: EFFECTIVE_FLOOR_SECS,
        })
    } else {
        Ok(())
    }
}

// Compile-time invariant: the effective floor can never regress below the hardcoded one,
// regardless of `BUILD_FLOOR_SECS`.
const _: () = assert!(EFFECTIVE_FLOOR_SECS >= HARDCODED_FLOOR_SECS);

#[cfg(test)]
mod tests {
    use super::{EFFECTIVE_FLOOR_SECS, check_floor};

    #[test]
    fn rejects_before_floor() {
        assert!(check_floor(EFFECTIVE_FLOOR_SECS - 1).is_err());
    }

    #[test]
    fn accepts_at_floor() {
        assert!(check_floor(EFFECTIVE_FLOOR_SECS).is_ok());
    }

    #[test]
    fn accepts_after_floor() {
        assert!(check_floor(EFFECTIVE_FLOOR_SECS + 1).is_ok());
    }
}