zc2 0.0.47

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! Identity of the running `zc` binary, as disclosed to peers and clients.
//!
//! Three facts, each answering a different question:
//!
//! * `version` — which release this claims to be.
//! * `git` — which source revision it was built from.
//! * `binary_sha256` — which artifact is actually executing.
//!
//! The third is the one that settles an argument. Two brokers can both report
//! `0.0.32` from the same commit and still be running different programs: a
//! dirty tree, a different target triple, a rebuild after a dependency moved.
//! Peers reconcile on the hash; the other two are for humans reading it.
//!
//! Disclosing the hash costs nothing in privacy. `zc` is MIT with published
//! releases, so the hash of a release binary is computable by anyone holding
//! the version string, and a [`BuildId`] carries no address and no secret —
//! the IP-free rule for client-facing surfaces is unaffected.

use std::path::Path;
use std::sync::OnceLock;

use serde::{Deserialize, Serialize};

/// Hex characters of `binary_sha256` shown in human output. Matches git's
/// short-hash convention: enough to tell builds apart at a glance.
pub const SHORT_HASH_LEN: usize = 12;

/// What binary a broker is running.
///
/// Every field defaults on the wire so a peer built before this existed still
/// deserializes. Such a peer reports nothing, which is itself the signal
/// "older than build disclosure".
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct BuildId {
    /// Crate semver, e.g. `0.0.32`.
    #[serde(default)]
    pub version: String,
    /// Short git hash the binary was built from, suffixed `-dirty` when the
    /// tree had uncommitted changes. `None` when built outside a checkout.
    #[serde(default)]
    pub git: Option<String>,
    /// Lowercase hex SHA-256 of the executable file.
    ///
    /// `None` when the running executable cannot be located or read — a
    /// container that unlinked its own binary, say. Never fatal: an unknown
    /// hash degrades reconciliation, it does not stop the broker.
    #[serde(default)]
    pub binary_sha256: Option<String>,
}

/// `version` parsed as `(major, minor, patch)` for ordering.
///
/// Only the leading numeric triple is read; a pre-release or build suffix
/// (`0.0.34-rc1`) orders as its release. Anything unparseable is `None`, and
/// callers treat that the same as "no version at all" rather than guessing.
pub fn version_triple(version: &str) -> Option<(u64, u64, u64)> {
    let core = version.trim().trim_start_matches('v');
    let core = core.split(['-', '+']).next()?;
    let mut it = core.split('.');
    let major = it.next()?.parse().ok()?;
    let minor = it.next().unwrap_or("0").parse().ok()?;
    let patch = it.next().unwrap_or("0").parse().ok()?;
    Some((major, minor, patch))
}

/// Whether a peer's disclosed version is at least `minimum`.
///
/// A peer that discloses NOTHING is not at least anything: build disclosure
/// arrived in zc#305, so silence dates the peer to before it. That is a real
/// answer, not a missing one, and it is why the default gate excludes such a
/// peer rather than giving it the benefit of the doubt.
pub fn meets_minimum(peer: Option<&BuildId>, minimum: (u64, u64, u64)) -> bool {
    peer.and_then(|b| version_triple(&b.version))
        .map(|v| v >= minimum)
        .unwrap_or(false)
}

impl BuildId {
    /// First [`SHORT_HASH_LEN`] hex chars of the binary hash.
    pub fn short_hash(&self) -> Option<&str> {
        let h = self.binary_sha256.as_deref()?;
        // A peer is not trusted to have sent 64 ASCII hex chars, so truncate
        // on a char boundary: a multi-byte value must shorten, never panic.
        let end = h
            .char_indices()
            .map(|(i, _)| i)
            .nth(SHORT_HASH_LEN)
            .unwrap_or(h.len());
        Some(&h[..end])
    }

    /// One-line label for human output: `0.0.32 (0447049) sha:ab12cd34ef56`,
    /// dropping whichever parts are unknown. `unknown` when nothing is.
    pub fn label(&self) -> String {
        let mut parts = Vec::new();
        if !self.version.is_empty() {
            parts.push(self.version.clone());
        }
        if let Some(g) = &self.git {
            parts.push(format!("({})", g));
        }
        if let Some(h) = self.short_hash() {
            parts.push(format!("sha:{}", h));
        }
        if parts.is_empty() {
            "unknown".to_string()
        } else {
            parts.join(" ")
        }
    }

    /// Whether this broker knows anything at all about its own build. A peer
    /// too old to disclose one reports `BuildId::default()`.
    pub fn is_known(&self) -> bool {
        !self.version.is_empty() || self.git.is_some() || self.binary_sha256.is_some()
    }

    /// Whether two brokers run the same program.
    ///
    /// The hash decides whenever both sides know theirs. When either does not,
    /// fall back to version+git: weaker (same commit built for two targets
    /// compares equal) but it never claims a match across differing versions,
    /// which is the comparison that matters for skew.
    pub fn same_build_as(&self, other: &BuildId) -> bool {
        match (&self.binary_sha256, &other.binary_sha256) {
            (Some(a), Some(b)) => a == b,
            _ => self.version == other.version && self.git == other.git,
        }
    }
}

/// Identity of this process's binary. Hashed once, on first call.
///
/// The hash is read from the file on disk rather than from memory: it is the
/// artifact that was installed and can be compared against a release asset,
/// not a checksum of the loaded image.
pub fn current() -> &'static BuildId {
    static CURRENT: OnceLock<BuildId> = OnceLock::new();
    CURRENT.get_or_init(|| BuildId {
        version: env!("CARGO_PKG_VERSION").to_string(),
        git: git_revision(),
        binary_sha256: std::env::current_exe().ok().and_then(|p| hash_file(&p)),
    })
}

/// The commit stamped in by `build.rs`, with a `-dirty` marker when the tree
/// it was built from had uncommitted changes.
fn git_revision() -> Option<String> {
    let hash = option_env!("ZC_GIT_HASH")?;
    Some(if option_env!("ZC_GIT_DIRTY") == Some("1") {
        format!("{}-dirty", hash)
    } else {
        hash.to_string()
    })
}

/// Lowercase hex SHA-256 of a file, streamed so a large binary never lands in
/// memory whole. `None` on any read error — callers treat an unknown hash as
/// missing information, never as an error to propagate.
pub fn hash_file(path: &Path) -> Option<String> {
    use std::io::Read;

    let mut file = std::fs::File::open(path).ok()?;
    let mut ctx = ring::digest::Context::new(&ring::digest::SHA256);
    let mut buf = [0u8; 64 * 1024];
    loop {
        match file.read(&mut buf) {
            Ok(0) => break,
            Ok(n) => ctx.update(&buf[..n]),
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
            Err(_) => return None,
        }
    }
    Some(hex::encode(ctx.finish().as_ref()))
}

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

    #[test]
    fn versions_order_numerically_not_lexically() {
        // "0.0.9" > "0.0.34" lexically; the whole point is that it is not.
        assert!(version_triple("0.0.34") > version_triple("0.0.9"));
        assert!(version_triple("0.1.0") > version_triple("0.0.99"));
        assert!(version_triple("1.0.0") > version_triple("0.9.9"));
        assert_eq!(version_triple("0.0.34"), Some((0, 0, 34)));
    }

    #[test]
    fn a_prerelease_or_v_prefix_orders_as_its_release() {
        assert_eq!(version_triple("v0.0.34"), Some((0, 0, 34)));
        assert_eq!(version_triple("0.0.34-rc1"), Some((0, 0, 34)));
        assert_eq!(version_triple("0.0.34+build7"), Some((0, 0, 34)));
        assert_eq!(version_triple("0.1"), Some((0, 1, 0)));
    }

    #[test]
    fn nonsense_is_none_rather_than_a_guess() {
        for bad in ["", "abc", "x.y.z", "..", "0.0.x"] {
            assert_eq!(version_triple(bad), None, "{bad}");
        }
    }

    /// The case the default gate exists for: three nodes on the measured mesh
    /// disclose no build at all, which dates them to before zc#305. Silence is
    /// an answer — "older" — not a missing value to be waved through.
    #[test]
    fn a_peer_that_discloses_nothing_does_not_meet_any_floor() {
        assert!(!meets_minimum(None, (0, 0, 1)));
        let silent = BuildId::default();
        assert!(!meets_minimum(Some(&silent), (0, 0, 1)));
    }

    #[test]
    fn a_peer_meets_a_floor_at_or_above_it() {
        let peer = BuildId {
            version: "0.0.34".into(),
            git: None,
            binary_sha256: None,
        };
        assert!(meets_minimum(Some(&peer), (0, 0, 34)), "equal passes");
        assert!(meets_minimum(Some(&peer), (0, 0, 30)), "newer passes");
        assert!(!meets_minimum(Some(&peer), (0, 0, 35)), "older is refused");
        assert!(
            !meets_minimum(Some(&peer), (0, 1, 0)),
            "older minor refused"
        );
    }
}

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

    #[test]
    fn current_reports_this_crate_and_a_64_hex_char_hash() {
        let id = current();
        assert_eq!(id.version, env!("CARGO_PKG_VERSION"));
        let hash = id
            .binary_sha256
            .as_deref()
            .expect("the test binary is readable, so it hashes");
        assert_eq!(hash.len(), 64, "SHA-256 is 32 bytes = 64 hex chars");
        assert!(hash
            .chars()
            .all(|c| c.is_ascii_hexdigit() && !c.is_uppercase()));
    }

    #[test]
    fn current_is_computed_once_and_stable() {
        assert_eq!(current(), current());
    }

    #[test]
    fn hash_file_matches_a_known_sha256() {
        // echo -n "" | sha256sum
        let dir = std::env::temp_dir().join(format!("zc-build-id-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let empty = dir.join("empty");
        std::fs::write(&empty, b"").unwrap();
        assert_eq!(
            hash_file(&empty).as_deref(),
            Some("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
        );
        // echo -n "abc" | sha256sum
        let abc = dir.join("abc");
        std::fs::write(&abc, b"abc").unwrap();
        assert_eq!(
            hash_file(&abc).as_deref(),
            Some("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn hash_file_is_none_for_a_path_that_is_not_there() {
        assert_eq!(hash_file(Path::new("/nonexistent/zc-binary")), None);
    }

    #[test]
    fn a_missing_build_block_deserializes_as_unknown() {
        // An old peer's body has no `build` key at all, and one built just
        // before the hash landed may send a version with no hash.
        let none: Option<BuildId> = serde_json::from_str("null").unwrap();
        assert!(none.is_none());
        let partial: BuildId = serde_json::from_str(r#"{"version":"0.0.31"}"#).unwrap();
        assert_eq!(partial.version, "0.0.31");
        assert_eq!(partial.git, None);
        assert_eq!(partial.binary_sha256, None);
        assert!(partial.is_known());
        assert!(!BuildId::default().is_known());
    }

    #[test]
    fn the_hash_decides_when_both_sides_have_one() {
        let a = BuildId {
            version: "0.0.32".into(),
            git: Some("0447049".into()),
            binary_sha256: Some("aa".repeat(32)),
        };
        // Same version and commit, different artifact: NOT the same build.
        let cross_compiled = BuildId {
            binary_sha256: Some("bb".repeat(32)),
            ..a.clone()
        };
        assert!(!a.same_build_as(&cross_compiled));
        assert!(a.same_build_as(&a.clone()));
    }

    #[test]
    fn without_a_hash_it_falls_back_to_version_and_commit() {
        let hashless = BuildId {
            version: "0.0.32".into(),
            git: Some("0447049".into()),
            binary_sha256: None,
        };
        let same_source = BuildId {
            binary_sha256: Some("aa".repeat(32)),
            ..hashless.clone()
        };
        assert!(hashless.same_build_as(&same_source));

        let older = BuildId {
            version: "0.0.31".into(),
            ..hashless.clone()
        };
        assert!(!hashless.same_build_as(&older));
    }

    #[test]
    fn label_drops_what_it_does_not_know() {
        assert_eq!(
            BuildId {
                version: "0.0.32".into(),
                git: Some("0447049-dirty".into()),
                binary_sha256: Some("ab12cd34ef56".to_string() + &"0".repeat(52)),
            }
            .label(),
            "0.0.32 (0447049-dirty) sha:ab12cd34ef56"
        );
        assert_eq!(
            BuildId {
                version: "0.0.32".into(),
                git: None,
                binary_sha256: None,
            }
            .label(),
            "0.0.32"
        );
        assert_eq!(BuildId::default().label(), "unknown");
    }

    #[test]
    fn short_hash_does_not_panic_on_a_stub_value() {
        // A peer is not trusted to send 64 chars.
        let stub = BuildId {
            binary_sha256: Some("abc".into()),
            ..Default::default()
        };
        assert_eq!(stub.short_hash(), Some("abc"));
    }
}